/*
 * Copyright (c) 2022-present Charles7c Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package top.continew.admin.card.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import top.continew.admin.card.mapper.WechatUserMapper;
import top.continew.admin.card.model.entity.WechatUserDO;
import top.continew.admin.card.model.query.WechatUserQuery;
import top.continew.admin.card.model.req.WechatUserReq;
import top.continew.admin.card.model.resp.WechatUserDetailResp;
import top.continew.admin.card.model.resp.WechatUserResp;
import top.continew.admin.card.service.UserWechatRelationService;
import top.continew.admin.card.service.WechatUserService;
import top.continew.starter.extension.crud.model.query.PageQuery;
import top.continew.starter.extension.crud.model.resp.PageResp;
import top.continew.starter.extension.crud.service.impl.BaseServiceImpl;

import java.util.List;

/**
 * 微信用户业务实现
 *
 * @author floyd
 * @since 2024/12/02 15:34
 */
@Service
@RequiredArgsConstructor
public class WechatUserServiceImpl extends BaseServiceImpl<WechatUserMapper, WechatUserDO, WechatUserResp, WechatUserDetailResp, WechatUserQuery, WechatUserReq> implements WechatUserService {

    @Resource
    private final UserWechatRelationService userWechatRelationService;

    @Override
    public Long saveUser(WechatUserReq userReq) {
        var openId = userReq.getOpenId();

        WechatUserDO userDO = new WechatUserDO();
        userDO.setOpenId(userReq.getOpenId());
        userDO.setNickname(userReq.getNickname());
        userDO.setAvatar(userReq.getAvatar());
        userDO.setGender(userReq.getGender());
        userDO.setCountry(userReq.getCountry());
        userDO.setProvince(userReq.getProvince());
        userDO.setCity(userReq.getCity());

        var existsFlag = baseMapper.lambdaQuery().eq(WechatUserDO::getOpenId, openId).exists();
        if (existsFlag) {
            var result = baseMapper.lambdaQuery().eq(WechatUserDO::getOpenId, openId);

            //修改用户信息
            baseMapper.update(result);
            return result.getEntity().getId();
        } else {
            //新增用户信息
            baseMapper.insert(userDO);

            return userDO.getId();
        }

    }

    @Override
    public PageResp<WechatUserResp> page(WechatUserQuery query, PageQuery pageQuery) {
        // 创建一个新的QueryWrapper对象
        QueryWrapper<WechatUserDO> queryWrapper = new QueryWrapper<>();

        // 处理nickname字段，添加别名前缀
        if (query.getNickname() != null && !query.getNickname().isEmpty()) {
            String aliasedNickname = "t1.nickname";
            queryWrapper.like(aliasedNickname, query.getNickname());
        }

        //处理queryType字段
        if (query.getQueryType() != null) {
            String tableNameAlias = "t3"; // 假设表别名是t3
            switch (query.getQueryType()) {
                case 1 ->
                    // 当queryType为1时，查询条件为t3.nickname is not null
                    queryWrapper.isNotNull(tableNameAlias + ".nickname");
                case 2 ->
                    // 当queryType为2时，查询条件为t3.nickname is null
                    queryWrapper.isNull(tableNameAlias + ".nickname");
                default -> {
                }
                // 如果queryType不是1或2，可以根据需要添加默认逻辑
                // 例如，可以不做任何处理，或者抛出一个异常来表示无效的queryType
                // 这里我们暂时选择不做任何处理
            }
        }

        //QueryWrapper<WechatUserDO> queryWrapper = this.buildQueryWrapper(query);
        super.sort(queryWrapper, pageQuery);

        IPage<WechatUserResp> page = baseMapper.queryWechatUserPage(new Page<>(pageQuery.getPage(), pageQuery
            .getSize()), queryWrapper);
        PageResp<WechatUserResp> pageResp = PageResp.build(page, super.getListClass());
        pageResp.getList().forEach(this::fill);
        return pageResp;
    }

    @Override
    public void beforeDelete(List<Long> ids) {

    }
}